package com.example.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/upload")
public class uploadController {

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.secretKey}")
    private String secretKey;

    @Value("${oss.bucketEndpoint}")
    private String bucketEndpoint;

    /**
     * 上传头像到阿里云oss
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadAvatar")
    public String upload(MultipartFile file) throws IOException {
        System.out.println("进来");
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();

        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKey,secretKey);

        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("你已创建Bucket :" + bucketName);
        } else {
            System.out.println("bucket不存在，创建Bucket: " + bucketName);
            ossClient.createBucket(bucketName);
        }

        //设计一个存储对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        System.out.println("文件名称：" + filename);
        String objectName = sdf.format(new Date()) + "/" + filename;

        //存储对象
        ossClient.putObject(bucketName,objectName,inputStream);
        String httpURL = bucketEndpoint +"/" + objectName;

        ossClient.shutdown();
        return  httpURL;
    }
}
